import { _decorator, Component, EventTouch, Node, UITransform, v2, v3 } from 'cc';
import { camera } from './camera';
const { ccclass, property } = _decorator;

@ccclass('syMoveButten')
export class syMoveButten extends Component {
    @property(Node)
    center: Node

    uiTran: UITransform

    //最大半径
    maxR = 40
    outDir = v2(0, 0)

    getJoyDir() {
        return this.outDir
    }
    start() {
        this.uiTran = this.node.getComponent(UITransform)
        this.openTouchEvent()
    }
    openTouchEvent() {
        //TOUCH_START同TOUCH_MOVE一样
        this.node.on(Node.EventType.TOUCH_START, this.onTouchMove, this)
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
        // this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this)

    }
    // onTouchStart(event: EventTouch) {
    //     const uiPos = event.getUILocation()
    //     const cPos = this.uiTran.convertToNodeSpaceAR(v3(uiPos.x, uiPos.y, 0))
    //     this.center.setPosition(cPos.x, cPos.y)
    // }
    onTouchMove(event: EventTouch) {
        const uiPos = event.getUILocation()
        const cPos = this.uiTran.convertToNodeSpaceAR(v3(uiPos.x, uiPos.y, 0))
        //三维方法
        const len = cPos.length()
        // //二维方法
        // const cx = cPos.x
        // const cy = cPos.y
        // const vec2 = v2(cx, cy)
        // //得到长度
        // const len = v2.length
        //归一化
        const dir = cPos.normalize()
        // 判断
        const scale = len > this.maxR ? this.maxR : len
        const out = dir.multiplyScalar(scale)
        this.center.setPosition(out.x, out.y)
        //做记录
        this.outDir.set(out.x, out.y)
    }
    onTouchEnd(event: EventTouch) {

        this.center.setPosition(0, 0)
        this.outDir.set(0, 0)
    }

    update(deltaTime: number) {
        const herox = this.node.parent.getScale().x
        if (herox <= 0) {
            this.node.setScale(1, 1)
        }
    }
}


